//
//  UserMainController.swift
//  FarmShare
//
//  Created by XingJian Li on 2018/3/15.
//  Copyright © 2018年 aykj. All rights reserved.
//

import Foundation

import Alamofire




class MainUserIndex: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    var tableView: UITableView!
    
    var CompleteArray = [CompleteModel]()

//    var dataModelArray = [MainUserModel]()
    
    var showTaskNameArray:[String]?=[]
    
    
    var shujuyuan: Array<String> = []
    
    var taskNumArray:[String]?=[]
    
    
    var taskNameArray:[String]?=[]
    

    var titleL :UILabel!
    
    var titleDL:UILabel!

    //adminUserName
    var adminUserName:String!
    
    //adminUserPic
    var adminUserPic:String!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden=false
        let manager = UserDefaults()
        let token: String? = manager.string(forKey:"tokens")  //根据关键字取值
  
        
        
        if token == nil {
            
            let login =   LoginViewController()
            self.navigationController?.pushViewController(login, animated: true)
            
        }
        else{
            
            self.NumData()
            
         
            
        }
      
    }
  
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title="个人中心"
        
        self.view.backgroundColor = UIColor.white
        
        let img = UIImage(named: "setting")
        
        let rightItem=UIBarButtonItem(image: img, style: UIBarButtonItemStyle.plain, target: self, action: #selector(rightItemButton))
        self.navigationItem.rightBarButtonItem=rightItem
        



    }
    @objc func rightItemButton(){
        print("设置")
        
        let  SettingVC =  SettingViewController()
        
        self.navigationController?.pushViewController(SettingVC , animated: true)
    }
    //我的待办
    func taskData(){
        
        
        let start:String? = "1"
        let pageSize:String? = "5"
        
        let manager = UserDefaults()
        
        
        let token: String? = manager.string(forKey:"tokens")  //根据关键字取值

        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/adminUserCenter/getMyTask"
        
        let json = "{\"token\":\"\(token!)\",\"start\":\"\(start!)\",\"pageSize\":\"\(pageSize!)\"}"
 
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
        
        Alamofire.request(request).responseJSON {
            (response) in
            
            
            print("sige====\(response)")
            if response.result.isSuccess {
                let json = JSON(response.data!)
                
                let array  = json["resultData"].array;
                
                for dataDic in  array!
                {
                    let model =   CompleteModel()

                    model.taskId = dataDic["taskId"].string
                    model.createTime = dataDic["createTime"].string
                    model.projectName = dataDic["projectName"].string
                    model.taskName = dataDic["taskName"].string
                    
                    model.projectStage = dataDic["projectStage"].string
                    model.projectNum = dataDic["projectNum"].string
                    model.informationRecordId = dataDic["informationRecordId"].string

                    self.CompleteArray.append(model)

                }
                
            
            }
            self.tableView.reloadData()
           
        }
        
    }
    //获取头像
    func loadData() {
        
        let manager = UserDefaults()
        
        
        let token: String? = manager.string(forKey:"tokens")  //根据关键字取值
        
        
        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/adminUserCenter/getPersonalMsg"
        
        let json = "{\"token\":\"\(token!)\"}"
       
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!
        
        
        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
      
        Alamofire.request(request).responseJSON {
            (response) in

            
            if response.result.isSuccess {
                let json = JSON(response.data!)

//                self.adminUserName  = json["adminUserName"].string
                
                self.adminUserName = json["adminUserName"].string
                
                self.adminUserPic  = json["adminUserPic"].string
          
            }
            
              self.tableView.reloadData()
          
        }
        
    }

    //获取四个状态
    func NumData() {

        let manager = UserDefaults()


        let token: String? = manager.string(forKey:"tokens")  //根据关键字取值
        
         print("1111===\(token!)")


        let urlString = "http://wwwqjzsyzcscom.aykj.net.cn/api/adminUserCenter/getProjectNum"
        

        let json = "{\"token\":\"\(token!)\"}"
        let url = URL(string: urlString)!
        let jsonData = json.data(using: .utf8, allowLossyConversion: false)!


        var request = URLRequest(url: url)
        request.httpMethod = HTTPMethod.post.rawValue
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData

        Alamofire.request(request).responseJSON {
            (response) in
            
            
      
            
            if response.result.isSuccess {
                let jsons = JSON(response.data!)

                let array  = jsons["resultData"].array;
                
                if array?.count == nil {
                    
                    
                    
                    UserDefaults.standard.removeObject(forKey: "tokens")
                    UserDefaults.standard.removeObject(forKey: "accounts")
                    UserDefaults.standard.removeObject(forKey: "names")
                    let login =   LoginViewController()
                    self.navigationController?.pushViewController(login, animated: true)
                    
                }else{
                    
                    for dataDic in  array!
                    {
                        
                        let showTaskName = dataDic["showTaskName"].string
                        let taskNum = dataDic["taskNum"].string
                        let taskName = dataDic["taskName"].string
                        self.showTaskNameArray?.append(showTaskName!)
                        self.taskNumArray?.append(taskNum!)
                        self.taskNameArray?.append(taskName!)
                        
                        
                    }
                    
                    
                    self.taskData()
                    self.loadData()
                    
                    
                    
                    
                    
                    self.tableView = UITableView(frame:self.view.frame, style:.grouped)
                    self.tableView.dataSource = self
                    self.tableView.delegate = self
                    //        self.tableView.showsHorizontalScrollIndicator = false
                    //        self.tableView.showsVerticalScrollIndicator = false
                    
                    self.tableView.tableFooterView = UIView.init()
                    
                    self.tableView.register(NSClassFromString("UserHeaderTableViewCell"), forCellReuseIdentifier: "UserHeaderTableViewCell")
                    self.tableView.register(NSClassFromString("EngineeringTableViewCell"), forCellReuseIdentifier: "EngineeringCell")
                    self.tableView.register(NSClassFromString("ContentTableViewCell"), forCellReuseIdentifier: "ContentTableViewCell")
                    self.view.addSubview(self.tableView)
                    self.tableView.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
                    
                }
                
              
            }
         
        }

    }
   
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }else if section == 1 {
            return 1
        }else{
            return self.CompleteArray.count
        }
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if  section == 0 {
            return 0
        }else if section == 1{
            return 10
        }else{
            return 40
        }
        
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 2{
            return "我的待办"
        }else{
            return " "
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   
        if indexPath.section == 0 {
            return 150
        }else if indexPath.section == 1{
            return 80
        }else{
            return 160
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
        if(indexPath.section == 0 ){
            
        
            
      
            let cell = UserHeaderTableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "UserHeaderTableViewCell")
            cell.backgroundColor = UIColor.init(r: 79, g: 122, b: 233, a: 1)
            
            //在谈项目
            cell.label1.addTarget(self,action:#selector(ConversationingButton), for: .touchUpInside)

            
            //签约项目
            cell.label2.addTarget(self,action:#selector(ContractButton), for: .touchUpInside)
        
            //开工项目
            cell.label3.addTarget(self,action:#selector(OpeningButton), for: .touchUpInside)
            //投产项目
            cell.label4.addTarget(self,action:#selector(productionButton), for: .touchUpInside)
            
            cell.selectionStyle = .none
            
            let manager = UserDefaults()
            
            let tokens = manager.string(forKey: "tokens")
            
            if tokens == nil{
                cell.nameLabel.isUserInteractionEnabled = true
                
                cell.nameLabel.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(openMerchantListVC)))
            }else{

                cell.nameLabel.isUserInteractionEnabled = false
                if self.adminUserPic != nil{
                     cell.HeadeImgView.sd_setImage(with: NSURL.init(string: "http://wwwqjzsyzcscom.aykj.net.cn/api/\(self.adminUserPic!)")! as URL, placeholderImage: UIImage.init(named: "morentouxiang"), options: [], progress: nil, completed:nil)
                }
               
                
                if self.adminUserName != nil{
                    cell.nameLabel.text = self.adminUserName
                }


                cell.label1.NumLabel.text = self.taskNumArray![0]
                cell.label1.nameLabel.text = self.showTaskNameArray![0]

                cell.label2.NumLabel.text = self.taskNumArray![1]
                cell.label2.nameLabel.text = self.showTaskNameArray![1]

                cell.label3.NumLabel.text = self.taskNumArray![2]
                cell.label3.nameLabel.text = self.showTaskNameArray![2]

                cell.label4.NumLabel.text = self.taskNumArray![3]
                cell.label4.nameLabel.text = self.showTaskNameArray![3]


                
            }
            
      
            return cell
            
            
        }else if( indexPath.section == 1){
            
            
            
            let cell = EngineeringTableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "EngineeringCell")
            //项目录入
            cell.Engineering.addTarget(self,action:#selector(EngineeringButton), for: .touchUpInside)
            //我的待办
            cell.MyJob.addTarget(self,action:#selector(MyJobClick), for: .touchUpInside)
            //我的已办
            cell.complete.addTarget(self,action:#selector(completeClick), for: .touchUpInside)
            //企业信息库
            cell.information.addTarget(self,action:#selector(informationClick), for: .touchUpInside)
            cell.selectionStyle = .none
            return cell
            
            
            
        }else{
            
            
            
            let cell = ContentTableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "ContentTableViewCell")
            let cellModel:CompleteModel = self.CompleteArray[indexPath.row]
             cell.ConversationingWithModel(model: cellModel)
            cell.selectionStyle = .none
            cell.StateButton.addTarget(self, action: #selector(StateButtonClicks(button:)), for: .touchUpInside)
            
            cell.PassButton.addTarget(self, action: #selector(PassButtonClicks(button:)), for: .touchUpInside)
            return cell
        }
        
    }
    
    //办理
    @objc func StateButtonClicks(button: UIButton)  {
        
        let cell1 = button.superview?.superview as! ContentTableViewCell
        let cellIndex = tableView.indexPath(for: cell1)
        
        
    }
    
    //进度查询
    @objc func PassButtonClicks(button: UIButton)  {
        let cell1 = button.superview?.superview as! ContentTableViewCell
        let cellIndex = tableView.indexPath(for: cell1)
        
        
        let cellModel:CompleteModel = self.CompleteArray[(cellIndex?.row)!]
        
        let LookAlreadyTaskVC =  LookAlreadyTaskViewController()
        LookAlreadyTaskVC.numIdString = cellModel.informationRecordId
        self.navigationController?.pushViewController(LookAlreadyTaskVC , animated: true)
        
    }
    
    
    //点击登录
    @objc func openMerchantListVC(){
        print("点击")
        
        let loginVC =  LoginViewController()
        
        self.navigationController?.pushViewController(loginVC , animated: true)
        
    }
    
    //在谈项目
    @objc func ConversationingButton()  {
        
        
        let ConversationingVC =  ConversationingViewController()
        ConversationingVC.titleString = "在谈项目"
        
      
        ConversationingVC.taskNameString = self.taskNameArray![0]
        self.navigationController?.pushViewController(ConversationingVC , animated: true)
        
    }
    //签约项目
    @objc func ContractButton()  {
        let ConversationingVC =  ConversationingViewController()
        ConversationingVC.titleString = "签约项目"
        ConversationingVC.taskNameString = self.taskNameArray![1]
        self.navigationController?.pushViewController(ConversationingVC , animated: true)
    }
    //开工项目
    @objc func OpeningButton()  {
        let ConversationingVC =  ConversationingViewController()
        ConversationingVC.titleString = "开工项目"
      ConversationingVC.taskNameString = self.taskNameArray![2]
        self.navigationController?.pushViewController(ConversationingVC , animated: true)
    }
    //投产项目
    @objc func productionButton()  {
        let ConversationingVC =  ConversationingViewController()
        ConversationingVC.titleString = "投产项目"
      ConversationingVC.taskNameString = self.taskNameArray![3]
        self.navigationController?.pushViewController(ConversationingVC , animated: true)
    }
    
    
    
    
    
    
    
    
    //项目录入
    @objc func EngineeringButton()  {
        print("项目录入")

      
        //实例化一个将要跳转的viewController
        let LuruVc = LuruViewController()
        //跳转
        self.navigationController?.pushViewController(LuruVc , animated: true)
        
        
        
        
    }
    //我的待办
    @objc func MyJobClick()  {
        print("我的待办")
        
        //实例化一个将要跳转的viewController
        let CompleteVc = CompleteViewController()
        //跳转
        self.navigationController?.pushViewController(CompleteVc , animated: true)
        
        
    }
    //我的已办
    @objc func completeClick()  {
        print("我的已办")
        
        
        //实例化一个将要跳转的viewController
        let alreadyVc = alreadyTasksViewController()
        //跳转
        self.navigationController?.pushViewController(alreadyVc , animated: true)
    }
    //企业信息库
    @objc func informationClick()  {
        print("企业信息库")
        
        //实例化一个将要跳转的viewController
        let EnterpriseVc = EnterpriseViewController()
        //跳转
        self.navigationController?.pushViewController(EnterpriseVc , animated: true)
        
        
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
    }

}











